<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <title>字典管理</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}" href="../../../../static/layui/css/layui.css"/>
    <link rel="stylesheet" th:href="@{/resources/zTree/css/zTreeStyle/zTreeStyle.css}"
          href="../../../../static/resources/zTree/css/zTreeStyle/zTreeStyle.css"/>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <style type="text/css">
        #rMenu {
            position: absolute;
            visibility: hidden;
            top: 0;
            background-color: #f8f9fa;
            border: 1px solid #009688;
            text-align: left;
            padding: 2px;
            z-index: 12345;
        }

        #rMenu ul li {
            margin: 1px 0;
            padding: 0 5px;
            cursor: pointer;
            list-style: none outside none;
            background-color: #DFDFDF;
        }

        .lion-content {
            display: flex;
            /* justify-content: space-around; */
            align-items: flex-start;
            justify-items: center;
        }

        .dict-parent-node {
            display: flex;
            justify-items: center;
            align-items: center;
        }

        .dict-parent-node > div {
            margin-right: 30px;
        }
    </style>
</head>
<body>
<div class="layui-layout layui-layout-admin">
    <div th:replace="/admin/share/_header :: header"></div>

    <!-- 左侧导航区域 -->
    <div th:replace="/admin/sys_mgt/share/_left_sidebar :: leftSidebar('dict')"></div>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <div class="layui-tab">
                <ul class="layui-tab-title">
                    <li>字典管理</li>
                </ul>
                <div class="layui-tab-content lion-content">
                    <div style="margin-right: 20px;">
                        <ul id="dictTree" class="ztree"></ul>
                    </div>
                    <div id="dictDeatils" class="layui-tab-item layui-show">
                        <div id="dictParentNode" class="dict-parent-node">
                            <div>
                                <span class="col-form-label font-weight-bold">字典名称:</span>
                                <span class="dict-name text-muted">Root</span>
                            </div>
                            <div>
                                <span class="col-form-label font-weight-bold">字典值:</span>
                                <span class="dict-key text-muted">Root</span>
                            </div>
                            <div>
                                <span class="col-form-label font-weight-bold">字典Key:</span>
                                <span class="dict-value text-muted">Root_Key</span>
                            </div>
                            <!-- <div>
                                <button type="button" class="btn btn-secondary btn-sm">修改</button>
                            </div> -->
                        </div>
                        <hr class="my-4">
                        <table class="layui-table" id="dictTable" lay-filter="dictTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div th:replace="/admin/share/_footer :: footer"></div>
</div>

<!-- 新增modal -->
<div class="modal fade" id="saveDictModal" tabindex="-1" role="dialog" aria-labelledby="saveDictModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="saveDictModalLabel">新建字典</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="saveDictForm" action="/admin/dicts" method="post">
                    <input type="hidden" name="id"/>
                    <input type="hidden" name="parentId"/>

                    <div class="form-group">
                        <label for="name" class="col-form-label">字典名称:</label>
                        <input type="text" class="form-control" name="name" id="name"/>
                    </div>
                    <div class="form-group">
                        <label for="dictValue" class="col-form-label">字典值:</label>
                        <input type="text" class="form-control" name="dictValue" id="dictValue"/>
                    </div>
                    <div class="form-group">
                        <label for="dictKey" class="col-form-label">字典Key值:</label>
                        <input type="text" placeholder="key值必须是惟一的，例如： KEY_XXX" class="form-control" name="dictKey"
                               id="dictKey"/>
                    </div>
                    <!-- <div class="form-group form-check">
                      <input class="form-check-input" type="checkbox" name="enabled" value="1" id="defaultCheck2">
                      <label class="form-check-label" for="defaultCheck2">
                          是否可用
                      </label>
                  </div> -->
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveDict();">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 右键菜单 -->
<div id="rMenu">
    <ul>
        <li id="m_add" onclick="addTreeNode();">增加节点</li>
        <li id="m_del" onclick="removeTreeNode();">删除节点</li>
    </ul>
</div>
<!-- table toolbar -->
<script type="text/html" id="dictOps">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script th:src="@{/layui/layui.js}" src="../../../../static/layui/layui.js"></script>
<script th:src="@{/resources/zTree/js/jquery.ztree.core.js}"
        src="../../../../static/resources/zTree/js/jquery.ztree.core.js"></script>

<script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>

<script type="text/javascript">
    function setParentNodeInfo(node) {
        var dictParentNode = document.getElementById('dictParentNode');
        dictParentNode.querySelector('.dict-name').innerHTML = node.name;
        dictParentNode.querySelector('.dict-key').innerHTML = node.dictKey;
        dictParentNode.querySelector('.dict-value').innerHTML = node.dictValue;
    }

    var rootDict = '[[${rootDict}]]';
    rootDict = JSON.parse(rootDict.replace(/&quot;/g, "\""));
    setParentNodeInfo(rootDict);

    layui.use(['element', 'layer', 'table'], function () {
        var element = layui.element, layer = layui.layer, table = layui.table;

        table.render({
            elem: '#dictTable',
            height: 400,
            url: '/admin/dicts/all',
            request: {
                pageName: 'page',
                limitName: 'size'
            },
            response: {
                statusCode: 200,
                dataName: 'rows',
                countName: 'totalCount'
            },
            page: true,
            cols: [
                [
                    {type: 'numbers', fixed: true},
                    {type: 'checkbox', fixed: true},
                    {field: 'name', width: 100, title: '字典名称'},
                    {field: 'dictKey', width: 100, title: '字典KEY值'},
                    {field: 'dictValue', width: 100, title: '字典值'},
                    {field: 'createTime', width: 180, title: '创建时间'},
                    {field: 'updateTime', width: 180, title: '最近一次更新时间'},
                    {fixed: 'right', align: 'center', width: 160, title: '操作', toolbar: '#dictOps'}
                ]
            ]
        });

        // 监听工具条
        table.on('tool(dictTable)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log('obj', obj);
            // 获得当前行数据
            var data = obj.data, layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'delete') {
                layer.confirm('真的删除该行吗？', function (index) {
                    removeDict(obj, index);
                });
            } else if (layEvent === 'edit') {
                var saveDictForm = document.getElementById("saveDictForm");
                for (var key in data) { // 为form表单load初始值
                    if (saveDictForm[key]) {
                        saveDictForm[key].value = data[key];
                    }
                }
                $('#saveDictModalLabel').html("编辑字典");
                $('#saveDictModal').modal('show');
            }
        });
    });

    // 为modal添加show 监听
    $('#saveDictModal').on('hide.bs.modal', function (event) { // 为modal添加hide 监听
        // event.target === this ： 均指modal ；event.relatedTarget： 谁触发了show modal事件，没有则为undefined
        var saveDictForm = this.querySelector('#saveDictForm');
        saveDictForm.reset(); // 重置form表单
        $('#saveDictModalLabel').html("新建字典");
    });

    // 删除数据
    function removeDict(obj, index) {
        // 向服务端发送删除指令
        $.ajax("/admin/dicts/" + obj.data.id, {
            type: 'delete',
            dataType: "json", //预期服务器返回的数据类型
        }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg('删除出错了');
        }).done(function (data, textStatus, jqXHR) {
            obj.del(); // 删除对应行（tr）的DOM结构
            /* 将zTree对应的node删除 */
            var node = zTree.getNodesByFilter(function (node) {
                return node.id === obj.data.id;
            }, true);
            zTree.removeNode(node);
        }).always(function () {
            layer.close(index);
        });
    }

    function saveDict() {
        var saveDictForm = document.getElementById("saveDictForm");
        var name = saveDictForm.name;
        if (name.value.length == 0) {
            layer.msg('字典名称是必填项');
            name.focus();
            return;
        }
        if (saveDictForm.dictValue.value.length == 0) {
            layer.msg('字典值是必填项');
            saveDictForm.dictValue.focus();
            return;
        }
        if (saveDictForm.dictKey.value.length == 0) {
            layer.msg('字典KEY是必填项');
            saveDictForm.dictKey.focus();
            return;
        }
        var formData = new FormData(saveDictForm);
        $.ajax({ // 向服务器发送数据
            url: "/admin/dicts",
            type: "POST",
            dataType: "json", //预期服务器返回的数据类型
            data: formData,
            contentType: false,
            processData: false
        }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(textStatus);
            console.log(errorThrown);
        }).done(function (data, textStatus, jqXHR) {
            if (formData.get('id')) {
                // 更新， 找到对应父节点更新
                var node = zTree.getNodesByFilter(function (node) {
                    return node.id === data.pId;
                }, true);
                zTree.reAsyncChildNodes(node, "refresh", false, function () {
                    layui.table.reload('dictTable', {
                        where: {
                            parentId: data.pId
                        }
                    });
                });
            } else {
                // 添加
                addSuceessCb(data);
            }
        }).always(function () {
            $('#saveDictModal').modal('hide');
        });
    }

    var setting = {
        async: {
            enable: true,
            type: 'GET',
            url: "/admin/dicts/childNodes",
            autoParam: ["id=pId"]
        },
        view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {
            onRightClick: onRightClick,
            onClick: onClick
        }
    };

    function onRightClick(event, treeId, treeNode) {
        if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
            zTree.cancelSelectedNode();
            showRMenu("root", event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    /* 选中哪一个，就查看其childNodes */
    function onClick(e, treeId, treeNode) {
        var nodes = zTree.getSelectedNodes();
        if (nodes.length) {
            var pNode = nodes[0];
            if (pNode.isParent) {
                layui.table.reload('dictTable', {
                    where: {
                        parentId: pNode.id
                    }
                });
                setParentNodeInfo(pNode);
            }
        }
    }

    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({
            "top": y + "px",
            "left": x + "px",
            "visibility": "visible"
        });

        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({
            "visibility": "hidden"
        });
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({
                "visibility": "hidden"
            });
        }
    }

    // 新增node成功后事件
    var addSuceessCb = function () {
    }; // 添加成功后的回调
    function addTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        if (nodes.length) {
            $('#saveDictModal').modal('show');
            $('#saveDictForm').children("input[name='parentId']").val(nodes[0].id);

            addSuceessCb = function (newNode) {
                newNode.checked = nodes[0].checked;
                zTree.addNodes(nodes[0], newNode);

                layui.table.reload('dictTable', {
                    where: {
                        parentId: newNode.pId
                    }
                });
            }
        }
    }

    function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            if (nodes[0].children && nodes[0].children.length) {
                var msg = "要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！";
                layer.confirm(msg, function (index) {
                    removeDict2(nodes[0], index);
                });
            } else {
                layer.confirm("确定删除吗？", function (index) {
                    removeDict2(nodes[0], index);
                });
            }
        }
    }

    function removeDict2(node, layerIndex) {
        $.ajax("/admin/dicts/" + node.id, {
            type: 'delete',
            dataType: "json", //预期服务器返回的数据类型
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('删除出错了');
        }).done(function (data, textStatus, jqXHR) {
            layui.table.reload('dictTable');
            zTree.removeNode(node);
        }).always(function () {
            layer.close(layerIndex);
        });
    }

    var zTree, rMenu;
    $(document).ready(function () {
        $.fn.zTree.init($("#dictTree"), setting, rootDict);
        zTree = $.fn.zTree.getZTreeObj("dictTree");
        rMenu = $("#rMenu");
    });
</script>
</body>
</html>